package com.wn.sk.member.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wn.common.api.Result;
import com.wn.common.jwt.JwtTemplate;
import com.wn.sk.Asserts;
import com.wn.sk.member.entity.User;
import com.wn.sk.member.entity.dto.UserDto;
import com.wn.sk.member.mapper.UserMapper;
import com.wn.sk.member.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员用户表 服务实现类
 * </p>
 *
 * @author Yellow Docker
 * @since 2022-11-08
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private JwtTemplate jwtTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录的方法
     *
     * 1、通过用户名和密码 和数据库中数据比对
     *
     * 2、成功
     *    1、创建token
     *    2、把token 存储到redis中 (token 是否过期)
     *
     * 3、失败
     *      返回失败结果
     *
     * @param UserDto
     * @return
     */
    @Override
    public Result<String> login(UserDto userDto) {

        //通过手机查询 数据中的用户信息
        String  mobile= userDto.getMobile();

        // Lambda 语法使用 Wrapper
        LambdaQueryWrapper<User> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        //条件查询  userMobile = 18566230000
        objectLambdaQueryWrapper.eq(User::getUserMobile,mobile);
        User loginUser = this.getOne(objectLambdaQueryWrapper);

        //判断 这个手机账号是否为null
        if (Objects.isNull(loginUser)){
            Asserts.failed("这个手机号的用户不存在....");
        }

        //比对
        if (BCrypt.checkpw(userDto.getPassword(),loginUser.getLoginPassword())){

            //创建一个token
            System.out.println("创建一个token = " + loginUser);
            Map<String,Object> map = new HashMap<>();
            map.put("userId",loginUser.getUserId());
            //创建一个token
            String token = jwtTemplate.createToken(map);

            //把token存储到redis中

            String key = "SKMEMBER:USER_ID:" + loginUser.getUserId();

            //把token存储到redis中 过期时间是 30min
            stringRedisTemplate.opsForValue().set(
                    key,
                    token,
                    30,
                    TimeUnit.MINUTES
            );
            return Result.ok(token);
        }else{
            Asserts.failed("手机号或者密码不正确....");
        }

        return Result.ok();
    }
}
